package com.example.blog_system.controller;

import com.example.blog_system.dto.ApiResponse;
import com.example.blog_system.dto.UserDto;
import com.example.blog_system.security.JwtTokenProvider;
import com.example.blog_system.security.UserPrincipal;
import com.example.blog_system.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<Map<String, Object>>> register(@Valid @RequestBody UserDto userDto) {
        try {
            UserDto registeredUser = userService.registerUser(userDto);
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", registeredUser.getId());
            data.put("username", registeredUser.getUsername());
            data.put("email", registeredUser.getEmail());
            
            return ResponseEntity.ok(ApiResponse.success("注册成功", data));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, e.getMessage()));
        }
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@Valid @RequestBody UserDto userDto) {
        try {
            // 执行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    userDto.getUsername(),
                    userDto.getPassword()
                )
            );

            // 设置认证信息到SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成JWT Token
            String jwt = tokenProvider.generateToken(authentication);
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

            Map<String, Object> data = new HashMap<>();
            data.put("id", userPrincipal.getId());
            data.put("username", userPrincipal.getUsername());
            data.put("email", userPrincipal.getEmail());
            data.put("token", jwt);

            return ResponseEntity.ok(ApiResponse.success("登录成功", data));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                .body(ApiResponse.error(401, "用户名或密码错误"));
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request, 
                                                  HttpServletResponse response,
                                                  @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication != null) {
                // 如果有token，将其加入黑名单
                if (token != null && token.startsWith("Bearer ")) {
                    String jwtToken = token.substring(7);
                    tokenProvider.invalidateToken(jwtToken);
                }

                // 清除session
                HttpSession session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }

                // 清除SecurityContext中的认证信息
                SecurityContextHolder.clearContext();

                // 使用SecurityContextLogoutHandler进行清理
                new SecurityContextLogoutHandler().logout(request, response, authentication);

                return ResponseEntity.ok(ApiResponse.success("注销成功"));
            }
            
            return ResponseEntity.ok(ApiResponse.success("用户未登录"));
        } catch (Exception e) {
            return ResponseEntity.status(500)
                .body(ApiResponse.error(500, "注销过程中发生错误"));
        }
    }

    @GetMapping("/check")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkToken(Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated() && 
            !"anonymousUser".equals(authentication.getPrincipal())) {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            Map<String, Object> response = new HashMap<>();
            response.put("id", userPrincipal.getId());
            response.put("username", userPrincipal.getUsername());
            response.put("email", userPrincipal.getEmail());
            return ResponseEntity.ok(ApiResponse.success("Token有效", response));
        }
        return ResponseEntity.status(401).body(ApiResponse.error(401, "Token无效或已过期"));
    }
} 